<template>
  <div class="app-container">
    <el-container v-loading="changeLoading"
                  element-loading-text="切换租户中..."
                  element-loading-spinner="el-icon-loading">

      <el-header class="filter-container">
        <div>

          <el-row>

            <el-button type="primary" icon="el-icon-tickets" @click="onExport(0)" class="filter-item">导出当前页</el-button>
            <el-button type="primary" icon="el-icon-top-right" @click="onExport(3)" class="filter-item">批量导出</el-button>
            <el-button type="primary" icon="el-icon-bottom-left" @click="onImport(0)" class="filter-item">批量导入
            </el-button>
            <el-link type="primary" style="margin-left: 20px;color:blue;" :href="template_excel">下载教师信息模板</el-link>
          </el-row>
          <el-row>

            <el-popover placement="bottom" trigger="click" style="text-align: center">
              <el-button plain slot="reference" @click="onCheckTitle">
                表头<i class="el-icon-caret-bottom el-icon--right"/>
              </el-button>
              <ul v-if="isShowTitleList" style="list-style-type:none"></ul>

              <ul style="list-style-type:none">
                <li style="margin-bottom: 10px">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="handleCheckAllChange">全选
                  </el-checkbox>
                </li>
                <li v-for="(item,index) in titleList">
                  <el-checkbox v-model="item.checked" :label="item.label" @change="handleCheckedOption"
                               :disabled="isFixTitle(item)"></el-checkbox>
                </li>
              </ul>
            </el-popover>
            <el-select v-model="condition.organize" placeholder="组织结构" :clearable="true"
                       @clear="()=>{condition.organize=''}" :disabled="isDisable" @change="changeTenant">
              <el-option
                v-for="item in organizeList"
                :key="item.id"
                :label="item.tenantName"
                :value="item.tenantId"
                :disabled="item.active==0">
              </el-option>
            </el-select>
            <el-select v-model="bind_statue" placeholder="绑定状态" style="width: 120px" :clearable="true"
                       @clear="()=>{condition.bindStatus=-1}">
              <el-option
                v-for="item in BIND_STATUS"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>

            <el-input v-model="condition.name" placeholder="姓名" style="width: 200px; "></el-input>
            <el-button type="primary" icon="el-icon-search" @click="onSearch()" style="width: 90px;">搜索</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" style="margin-left:50px">添加</el-button>

          </el-row>

        </div>


      </el-header>
      <el-main>
        <el-table
          ref="singleTable"
          :data="temperList"
          style="margin-top:40px; "
          v-loading="listLoading"
          highlight-current-row
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#e1e4e5',color:'#80878f'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left">

          </el-table-column>
          <el-table-column align="center" v-for="(item,index) in checkTitleList" :label="item.label" :key="item.key"
                           min-width="80px">
            <!--                           :width="item.width">-->
            <template slot-scope="scope">
              <div style="padding:0;display: block;" v-if="item.label==='头像'">
                <el-popover
                  placement="right"
                  width="390"
                  height="567"
                  trigger="hover"
                >
                  <el-image
                    :src="scope.row.icon"
                  >
                  </el-image>
                  <el-image slot="reference"
                            style="width: 39px; height: 56px"
                            :src="scope.row.icon"
                  >
                  </el-image>
                </el-popover>
              </div>

              <!--              <p v-else-if="item.label==='年级'">{{ GRADE[scope.row[item.value]].label }}</p>-->
              <p v-else-if="item.label==='性别'">{{ SEX[scope.row[item.value]].label }}</p>

              <p v-else-if="item.label==='组织结构'">
                {{ findObjByProp('tenantId', scope.row[item.value], organizeList).tenantName }}</p>
              <p v-else-if="item.label==='绑定状态'">
                <el-tag
                  :type="BIND_STATUS[scope.row[item.value]].type"
                >
                  {{ BIND_STATUS[scope.row[item.value]].label }}
                </el-tag>
              </p>

              <p v-else-if="item.label==='用户状态'">
                <!--                <el-tag-->
                <!--                  :type="ACTIVE[scope.row[item.value]].type"-->
                <!--                >-->
                <!--                  {{ ACTIVE[scope.row[item.value]].label }}-->
                <!--                </el-tag>-->

                <!--                {{ scope.row.active }}-->
                <el-switch
                  v-model="scope.row.active==1"
                  :width="60"
                  active-text="启用"
                  inactive-text="禁用"
                  :class="switchs"
                  @change="handleModifyStatus(scope.row)"
                >

                </el-switch>

              </p>
              <p v-else> {{ scope.row[item.value] }}</p>

            </template>
          </el-table-column>


          <el-table-column align="center" label=操作 width="270" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <!--              <el-button size="small" :type="PAY_STATUS[scope.row.pay_status].type" @click="handlePayStatus(scope.row)">-->
              <!--                {{ PAY_STATUS[scope.row.pay_status].label }}-->
              <!--              </el-button>-->
              <el-button type="danger" size="small" @click="handleDelete(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--        <el-pagination-->
        <!--          style="margin-top: 20px"-->
        <!--          @size-change="handleSizeChange"-->
        <!--          @current-change="handleCurrentChange"-->
        <!--          :current-page="1"-->
        <!--          :page-sizes="[50, 60, 70, 80]"-->
        <!--          :page-size="100"-->
        <!--          layout="total, sizes, prev, pager, next, jumper"-->
        <!--          :total="temperList.length">-->
        <!--        </el-pagination>-->

        <pagination v-show="totle >0" :total="totle " :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                    @pagination="getTeachers"/>


        <!--      创建用户面板-->
        <el-dialog

          :title="dialogTitle[dialogType]"
          :visible.sync="dialogVisible"
          :close-on-click-modal=false
          top="5vh">

          <el-form
            ref="studentFrom"
            :model="temper"
            :rules="rules"
            label-width="100px"
            style=" width: 80%; margin-left:50px;">

            <el-form-item label="组织结构：" prop="organize">
              <el-select v-model="temper.organize" placeholder="学校" style="width: 150px"
                         :disabled="isDisable||condition.organize!=''">
                <el-option
                  v-for="(item,index) in organizeList"
                  :key="index"
                  :label="item.tenantName"
                  :value="item.tenantId"
                  :disabled="item.active==0">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="姓名：" prop="name">
              <el-input v-model.trim="temper.name" maxLength="16"></el-input>
            </el-form-item>
            <el-form-item label="科目：">
              <el-input v-model.trim="temper.subject"></el-input>
              <!--                      <span class="underInputWords">字母、数字、下划线</span>-->
            </el-form-item>
            <el-form-item label="性别：">
              <el-radio v-model="temper.sex" :label="0">男</el-radio>
              <el-radio v-model="temper.sex" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="电话：" prop="tel">
              <el-input v-model="temper.tel" maxLength="11"></el-input>
            </el-form-item>

            <el-form-item label="个人简介：">
              <!--              <el-input v-model="temper.describe"></el-input>-->
              <el-input
                type="textarea"
                :rows="10"
                maxlength="300"
                show-word-limit
                v-model="temper.describe"></el-input>
            </el-form-item>


            <el-form-item>
              <div style="text-align:right;">
                <el-button type="danger" @click="cancelDialog('studentFrom')">取消</el-button>
                <el-button type="primary" @click="confirmDialog(dialogType)">确认</el-button>
              </div>
            </el-form-item>
          </el-form>

        </el-dialog>


        <!--      批量上传面板-->
        <el-drawer

          :visible.sync="isUpload"
          direction="ttb"
          :before-close="handleCloseUpload"
          size="50%">
          <Uploadexcel style="text-align: center" :tape-data="temper" :on-success="handleSuccessExcel"
                       :upload-path="upload_excel"/>

          <!--          <upload-excel-component style="text-align: center" :tape-data="tapeDateExcel" :on-change="handleSuccessExcel"  />-->
        </el-drawer>


      </el-main>

    </el-container>
  </div>
</template>

<script>
import Link from '@/layout/components/Sidebar/Link'
import switchs from '@/styles/switch.scss'
import { isInteger, validatePhone } from '@/utils/validate'
import Uploadexcel from '@/components/UploadExcel/index.vue'
import { isEmpty, parseTime } from '@/utils'
import { addTeacher, deleteTeacher, getTeachers, getTeachersCondition, updateTeacher } from '@/api/teacher'
import { findObjByProp } from '@/utils/utilc'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'
import { addConsumerHXY, delConsumerHXY } from '@/api/hxy' // secondary package based on el-pagination

const defaultCondition = {
  organize: '',
  gradeno: '',
  classno: '',
  name: '',
  bindStatus: -1,//绑定状态
  active: -1,//激活状态
  payStatus: -1,//支付状态
  bindcode: ''//绑定码
}

const defaultTemper = {
  key: '',
  icon: 'https://iptv.zhixue100.com.cn/icon/t.jpg',
  name: '',
  sex: 0,
  subject: '',//科目：varchar 具体名称，因为是学校自定义的，没有统一命名
  tel: '',
  bind_status: '0',
  bindcode: '',
  organize: '0',
  describe: '',//个人简介
  active: '1'//激活状态

}

const organize = [
  { id: '0', label: '未选择' },
  { id: '1', label: '汉唐和雅' },
  { id: '2', label: '金马小学' },
  { id: '3', label: '高新区试验小学' }
]

const classList = [
  { id: '0', label: '未选择' },
  { id: '1', label: '1' },
  { id: '2', label: '2' },
  { id: '3', label: '3' },
  { id: '4', label: '4' },
  { id: '5', label: '5' }
]

const defaultTitleName = [
  { key: 0, value: 'key', label: 'ID', width: 50, checked: true },
  { key: 1, value: 'icon', label: '头像', width: 120, checked: true },
  { key: 2, value: 'name', label: '姓名', width: 120, checked: true, disabled: true },
  { key: 3, value: 'sex', label: '性别', width: 80, checked: true },
  { key: 4, value: 'subject', label: '科目', width: 100, checked: true },
  { key: 5, value: 'tel', label: '电话', width: 150, checked: true },
  { key: 6, value: 'bindcode', label: '绑定码', width: 150, checked: true },
  { key: 7, value: 'bind_status', label: '绑定状态', width: 150, checked: true },
  { key: 8, value: 'active', label: '用户状态', width: 120, checked: true },
  { key: 9, value: 'tel', label: '个人简介', width: 200, checked: true },
  { key: 10, value: 'organize', label: '组织结构', width: 200, checked: true }
]

/***
 * 模拟用科目列表，后面根据实际情况舍取
 * */
const defaultSubject = [
  { key: 0, label: '科目一' },
  { key: 1, label: '科目二' },
  { key: 2, label: '科目三' },
  { key: 3, label: '科目四' },
  { key: 4, label: '科目五' },
  { key: 5, label: '科目六' }
]
/**
 * 列表中固定显示项
 * @type {string[]}
 */
const defaultCheckFixTitle = [
  '姓名',
  '性别',
  '科目',
  '电话'
]

export default {
  name: 'teacher',
  components: { Link, Uploadexcel, Pagination },
  data() {
    return {

      rules: {
        organize: [{ required: true, message: '不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        order_type: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入正确手机号', trigger: 'blur', validator: validatePhone }, {
          validator: isInteger,
          trigger: 'blur'
        }]
      },
      input_toolbar: '',
      isUpload: false,

      isShowTitleList: true,

      dialogTitle: ['创建', '编辑'],
      temper: Object.assign({}, defaultTemper),
      temperList: [],
      temperListTotle: [],

      tableHeader: [],
      roleList: [],
      dialogVisible: false,
      dialogType: '0',
      organize_id: 0,//组织机构id
      // organizeList: organize,//组织机构列表
      organizeList: this.$global.ORGANIZELIST(),//组织机构列表

      titleList: defaultTitleName,
      checkTitleList: defaultTitleName,

      isCheckAll: true,//表头项，全选状态
      isIndeterminate: false,

      props: { multiple: true, emitPath: false },

      str_tableRowClassName: '',

      tempGrade: '',
      tempClass: '',
      tempOrganize_id: '',
      bindId: '',

      condition: defaultCondition,

      parentList: [],
      isParentListEdit: [],

      BIND_STATUS: this.$global.BIND_STATUS,

      GRADE: [],
      CLASS: classList,
      SEX: this.$global.SEX,
      ACTIVE: this.$global.ACTIVE,

      selectList: '',
      multipleSelection: [],
      downloadLoading: false,
      filename: 'teachers',//文件名称

      //----excel相关-----------
      uploadfiles: [],
      tapeDateExcel: {//上传excel时用到的部分参数
        actid: '',
        name: '题库',//固定名称
        codename: 'qusbank',//固定名称
        url: '',             //此项未空
        auther: 'cxy',
        excelurl: 'this.pt_type.server',        //excel保存的路径
        modifytime: parseTime(new Date()),
        platform: 'this.platformKey'
      },

      switchs: switchs, //滑动按钮样式css
      template_excel: this.$global.TEMPLATE_EXCEL[1],
      upload_excel: this.$global.UPLOAD_EXCEL[1],
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 30
      },
      totle: 0,
      changeLoading: false,
      hxy_structure: 0

    }

  },

  created() {
    if (this.user_role == 'RA0003') {
      this.condition.organize = this.user_organize
    }
    // this.getTeachers()
   this.init()
  },

  computed: {
    bind_statue: {
      get() {

        if (this.condition.bindStatus < 0) {
          return ''
        }
        return this.condition.bindStatus
      },
      set(val) {
        this.condition.bindStatus = val
      }
    },

    pay_statue: {
      get() {
        if (this.condition.payStatus < 0) {
          return ''
        }
        return this.condition.payStatus
      },
      set(val) {
        this.condition.payStatus = val
      }
    },
    ...mapGetters([
      'name',
      'avatar',
      'user_organize',
      'user_role',
      'user_routes'
    ]),

    isDisable: {
      get() {
        return this.user_role == 'RA0003' ? true : false
      },
      set(val) {
      }
    }

  },
  watch: {},

  methods: {


    async init(){
      this.GRADE = await this.$global.GRADE_SYS()
      this.organizeList = await this.$global.ORGANIZELIST()//组织机构列表
    },
    /**
     * 本地数据和服务器数据格式转换
     *
     * @param local 本地数据
     * @param server 服务端数据
     * @param type 转换类型 1 服务端转本地 other：本地转服务端
     *
     *
     * */
    server_data_convert(local, server, type) {

      if (type == 1) {
        local.key = server.id ,
          local.icon = server.icon,
          local.name = server.name,
          local.bindcode = server.bindcode,
          local.bind_status = server.bindStatus,
          local.subject = server.subject,
          local.sex = server.sex,
          local.tel = server.tel ,
          local.organize = server.organize,
          local.describe = server.description,
          local.active = server.active
      } else {
        server.id = local.key,
          server.icon = local.icon ,
          server.name = local.name  ,
          server.bindcode = local.bindcode ,
          server.bindStatus = local.bind_status  ,
          server.subject = local.subject ,
          server.sex = local.sex ,
          server.tel = local.tel  ,
          server.organize = local.organize  ,
          server.description = local.describe ,
          server.active = local.active
      }

    },

    /**
     * 表头切换
     */
    handleCheckAllChange(val) {
      console.log('handleCheckAllChange==' + val)
      // this.checkTitleList = this.titleList.filter(function(obj, index) {
      //     obj.cheched = this.isCheckAll
      //   return obj.checked
      // })

      this.checkTitleList = []
      for (let index in this.titleList) {
        if (!val) {
          let bool = defaultCheckFixTitle.some((value) => {
            // console.log("value="+value)
            return value == this.titleList[index].label
          })
          if (bool) {
            this.titleList[index].checked = true
            this.checkTitleList.push(this.titleList[index])
          } else {
            this.titleList[index].checked = val
          }

        } else {
          this.titleList[index].checked = val
          this.checkTitleList.push(this.titleList[index])
        }
      }

      // this.checkTitleList = val ? this.titleList : []
      this.isIndeterminate = false

      // if(this.isCheckAll){
      //   for (let item in this.checkTitleList) {
      // item.checked = val
      // console.log("item.checked=="+JSON.stringify(this.checkTitleList))
      // }
      // }

    },

    handleCheckedBoxGroup(value) {

      let checkedCount = value.length
      this.isCheckAll = checkedCount === this.checkTitleList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkTitleList.length

      // console.log("check-group onchange =="+JSON.stringify(value))

    },

    isFixTitle(item) {

      let bool = defaultCheckFixTitle.some(function(value) {
        return value == item.label
      })
      return bool
    },

    handleCheckedOption(val) {
      // console.log("handleCheckedOption onchange =="+val)
      this.checkTitleList = this.titleList.filter(function(obj, index) {

        return obj.checked

      })

      let checkedCount = this.checkTitleList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.titleList.length

      // console.log("handleCheckedOption onchange =="+checkedCount+"  ")

    },
    isCheck(val) {
      // if (this.checkTitleList.length > 0) {
      //   let arr = this.checkTitleList
      //   return arr.some(function(obj, index, arr) {
      //
      //     return obj.label == val
      //   })
      // } else {
      //   return false
      // }
// console.log("check-box onchange ")
    },

    onCheckTitle() {
      this.isShowTitleList = this.isShowTitleList ? false : true

      // console.log("item.checked=2="+JSON.stringify(this.checkTitleList))

    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    tableRowClassName({ row, rowIndex }) {
      if (row.active == 0) {
        return this.str_tableRowClassName
      }
      // return 'alive-row';

      // let self = this
      // for(let i=0;i<self.selectList.length;i++) {
      //   console.log("rowIndex="+rowIndex+"   "+self.selectList[i])
      //
      //   if (rowIndex === self.selectList[i]) {
      //     return 'alive-row';
      //   }
      // }
    },

    async changeTenant(tenant) {

      console.log('切换租户：' + tenant)

      if (tenant != null && tenant != '') {
        let tenantName = findObjByProp('tenantId', tenant, this.organizeList).tenantName
        this.changeLoading = true
        await this.$global.CHANGE_TENANT(tenant).then(
          (res) => {
            // console.log('changeTenant=true='+res)
            this.changeLoading = false
            this.condition.organize = tenant

            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: '【' + tenantName + '】切换成功!',
              type: 'success',
              duration: 1500

            })
          },
          () => {
            this.condition.organize = ''
            this.changeLoading = false
            this.$notify({
              title: 'Error',
              dangerouslyUseHTMLString: true,
              message: '【' + tenantName + '】切换失败!',
              type: 'error',
              duration: 1500

            })
          }
        ).catch(error => {
          this.condition.organize = ''
          this.changeLoading = false
          this.$notify({
            title: 'Error',
            dangerouslyUseHTMLString: true,
            message: '【' + tenantName + '】切换异常!',
            type: 'error',
            duration: 1500

          })
        })
        this.temperList = []
      }
    },
    onSearch() {

      if (this.condition.organize != null && this.condition.organize != '') {

        // if (isEmpty(this.condition.bindStatus))
        //   this.condition.bindStatus =-1
          this.getTeachers()
      } else {

        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
      }
    },

    onCreate(type) {

      if (this.condition.organize == null || this.condition.organize == '') {
        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
        return false
      }
      this.dialogType = 0
      this.dialogVisible = true
      this.$nextTick(() => {
        this.temper = Object.assign({}, defaultTemper)
        // if(this.user_role=='RA0003')
        //   this.temper.organize = this.user_organize

        this.temper.organize = this.condition.organize

      })

      console.log('onCreate==' + JSON.stringify(this.temper))

    },

    handleCloseUpload(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },

    handleSuccessExcel({ file, fileList }) {
      // this.temperList = results
      // console.log('teacher上传Excel=' + JSON.stringify(results[0]))
      // this.tableHeader = header
      if (file.response.code == '20000') {
        this.getTeachers()
      }
    },

    beforeUploadExcel(file) {
      this.uploadfiles = file
      console.log('this.uploadfiles==' + this.uploadfiles[0])
      const isLt1M = file.size / 1024 / 1024 < 10

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '最大不超过10M',
        type: 'warning'
      })
      return false
    },

    /***
     * 工具栏-导入按钮
     *
     * **/
    onImport(type) {
      if (this.condition.organize == null || this.condition.organize == '') {
        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
      } else {
        this.upload_excel = this.$global.UPLOAD_EXCEL[1] + '/' + this.condition.organize
        console.log('组织结构：' + this.upload_excel)
        this.isUpload = this.isUpload ? false : true
      }
      // this.getHeaderExcel(this.checkTitleList,"label")

    },

    /***
     * 工具栏-导出按钮
     *
     * **/
    onExport(type) {

      if(type==0){
        if (this.multipleSelection.length) {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
            // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
            const tHeader = this.getHeaderExcel(this.checkTitleList, 'label')
            // tHeader.push('激活状态')
            const filterVal = this.getHeaderExcel(this.checkTitleList, 'value')
            // filterVal.push('active')
            const list = this.multipleSelection
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename
            })
            this.$refs.singleTable.clearSelection()
            this.downloadLoading = false
          })
        } else {
          this.$message({
            message: '请选择要导出的数据',
            type: 'warning'
          })
        }
      }else if(type==3){
        if (this.temperListTotle.length) {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
            // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
            const tHeader = this.getHeaderExcel(this.checkTitleList, 'label')
            // tHeader.push('激活状态')
            const filterVal = this.getHeaderExcel(this.checkTitleList, 'value')
            // filterVal.push('active')
            const list = this.temperListTotle
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename
            })
            this.$refs.singleTable.clearSelection()
            this.downloadLoading = false
          })
        } else {
          this.$message({
            message: '请选择要导出的数据',
            type: 'warning'
          })
        }
      }


    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))

      // return jsonData.map(v => filterVal.map(j => {
      //   // console.log("j=="+j+" "+v[j])
      //   if(j=="gradeno"){
      //
      //     return this.$global.GRADE_LOCAL[v[j]]
      //
      //   }else if(j=="classno"){
      //     // v[j]
      //     return v[j]+"班"
      //   }else{
      //     return v[j]
      //   }
      //
      // }))
    },
    /***
     * 操作-编辑按钮
     *
     * **/
    handleEdit(item) {
      this.dialogType = 1
      this.dialogVisible = true
      this.temper = item
    },

    /***
     * 操作-删除按钮
     *
     * **/
    handleDelete(item, index) {
      console.log('index==' + index)

      this.$confirm('确定要删除此条信息吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let{code} = await deleteTeacher(item.bindcode)
        if(code=='20000'){
          await delConsumerHXY(item.bindcode)
          // console.log("删除教书="+JSON.stringify(res));
          // if(data.message=="删除用户成功"){
            this.temperList.splice(index, 1)
            this.totle = --this.totle < 1 ? 0 : this.totle

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          // }else{
          //   this.$message({
          //     type: 'error',
          //     message: '删除失败HXY !'
          //   })
          // }

        }else{
          this.$message({
            type: 'error',
            message: '删除失败 !'
          })
        }

      }).catch(err => {
        console.error(err)
      })

    },

    /***
     *
     *【创建/编辑】对话框取消按钮
     *
     * */
    cancelDialog(fromname) {
      this.dialogVisible = false
      this.$refs[fromname].resetFields()
    },

    /***
     *
     *【创建/编辑】对话框确定按钮
     *
     * */
    async confirmDialog(_dialogType) {

      this.$refs['studentFrom'].validate(async(valid) => {
        if (valid) {
          let diaType = this.dialogType
          let server = {}
          this.server_data_convert(this.temper, server, 0)

          if (diaType == 0) {//创建
            const { data } = await addTeacher(server)
            this.temper.key = data.id
            this.temper.bindcode = data.bindcode
            console.log('temper==' + JSON.stringify(this.temper))

            //-----华栖云------------------
            let gradeName = findObjByProp('kcode', this.temper.gradeno, this.GRADE).label

            // let role_ids = await this.$global.getROLE_ID_HXY('RA1001')
            let role_ids = '教师'
            let tenantName = findObjByProp('tenantId', this.condition.organize, this.organizeList).tenantName

            this.hxy_structure = await this.$global.GET_HXY_STRUCTURE(tenantName)
            let structure_ids = this.hxy_structure

            let hxy_data = {
              role_name: role_ids,
              // structure_name: gradeName+this.CLASS[parseInt(this.temper.classno)].label,//
              structure_name: structure_ids,//
              account: this.temper.bindcode,
              // phone: this.temper.tel + '',
              realname: this.temper.name,
              // password: this.temper.bindcode + this.temper.organize,
              password: this.$global.PWS_STU_TEA,

              bindcode: this.temper.bindcode
              // pay_status: 0,
              // expire: 1,
              // iptv_bindcode: '1'
            }
            let {} = await addConsumerHXY(hxy_data)
            //-----华栖云------------------

            this.temperList.push(this.temper)

          } else {
            await updateTeacher(this.temper.key, server)
            for (let index = 0; index < this.temperList.length; index++) {
              if (this.temperList[index].key === this.temper.key) {
                this.temperList.splice(index, 1, Object.assign({}, this.temper))
                break
              }
            }
          }

          // this.cancelDialog('studentFrom')
          this.dialogVisible = false
          console.log('temper=tel=' + this.temper.tel)
        } else {

          console.log('error submit!!')
          return false
        }
      })

    },

    async getTeachers() {

      this.listLoading = true
      // this.GRADE = await this.$global.GRADE_SYS()
      // this.organizeList = await this.$global.ORGANIZELIST()//组织机构列表
      // console.log("zuzhijiajgou =="+JSON.stringify(this.organizeList))

      this.temperList = []
      this.temperListTotle = []
      let start = this.listQuery.limit * this.listQuery.page
      let end = this.listQuery.limit * (this.listQuery.page - 1)

      //发起网络请求后page和limit会被重置，原因未知
      let clickPage = this.listQuery.page
      let clickLimit = this.listQuery.limit

      if (this.condition.organize != null && this.condition.organize != '') {

        // let _condition = Object.assign({},this.condition)
        // if(isEmpty(_condition.bindStatus)) _condition.bindStatus = -1
        // if(isEmpty(_condition.active)) _condition.active = -1


        const res = await getTeachersCondition(this.condition)
        this.temperList = []
        for (let i = 0; i < res.data.length; i++) {
          let temp = Object.assign({}, this.temper)
          this.server_data_convert(temp, res.data[i], 1)
          // this.temperList.push(temp)
          this.temperListTotle.push(temp)

        }
        this.totle = this.temperListTotle.length
        this.temperList = this.temperListTotle.filter((item, index) => index < start && index >= end)

      }

      setTimeout(() => {
        this.listLoading = false
      }, 1.5 * 1000)

    },

    /***
     * 启用状态修改
     * @param row
     */
    async handleModifyStatus(row) {

      // console.log('switch===' + row.active)
      let words = ''
      let type = ''
      row.active = row.active == 0 ? 1 : 0
      // console.log('switch===' + row.active)
      let server = {}
      this.server_data_convert(row, server, 0)
      const { data, code } = await updateTeacher(server.id, server)

      if (code == '20000') {
        if (row.active == 0) {
          this.str_tableRowClassName = 'alive-row'
          words = '教师将无法使用此账号'
          type = 'warning'
        } else {
          this.str_tableRowClassName = ''
          words = '教师可以使用此账号'
          type = 'success'
        }

        this.$message({
          message: '操作成功:' + words,
          type: type
        })
      }

    },

    handlePayStatus(row) {

      // row.pay_status = row.pay_status == 0 ? 1 : 0

    },

    getHeaderExcel(array, value) {

      let arr = []
      array.forEach(e => {
        if (e.checked) {
          arr.push(e[value])
        }
      })

      // let arr = array.filter(function(item) {
      //
      //   return item[value]
      // });

      // console.log("Excel Header=="+JSON.stringify(arr))
      return arr

    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },

    findObjByProp(name, value, arr) {
      return findObjByProp(name, value, arr)
    }

  }

}
</script>

<style scoped>
.filter-item {
  /*float: right;*/
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .alive-row {
  /*background: #dc707d;*/
  background: #DCDFE6;
}

/*.upload-demo {*/
/*  text-align: center;*/
/*  vertical-align: middle;*/
/*  margin-top: 0;*/
/*  width: 50%;*/
/*}*/


</style>
<style>
.el-table th {
  display: table-cell !important;
}
</style>
